# -*- coding: utf-8 -*-
import re
import logging
import json
import datetime

# from datetime import timedelta

from bs4 import BeautifulSoup

from django.contrib.auth.models import User as AuthUser
from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify
from django.core import serializers
from django.utils import timezone
from blog.models import *

from blog import dao, tools, wp

logger = logging.getLogger('blog.fedoramagazine')


class Command(BaseCommand):
    help = 'fetch the specified book from it-ebooks.info'
    slug_prefix = 'fedoramagazine-'
    email_suffix = '@fedoramagazine.org'
    host = 'https://fedoramagazine.org/'

    def add_arguments(self, parser):
        parser.add_argument('from_page', type=int)

    def parse_page(self, url):
        logger.debug(url)
        html = tools.get_content(url, False)
        if not html:
            logging.error("can't get url " + url)
        soup = BeautifulSoup(html, "html.parser")
        for part in soup.find_all('div', class_='post-container'):
            blog_id = part.find(
                'div', class_='post').get('id').replace('post-', '')
            h2 = part.find('h2', class_='post-title').find('a')
            title = h2.get('title')
            url = h2.get('href')
            media = part.find(
                'div', class_='featured-media').find('img').get('src')
            meta = part.find('a', class_='post-date').string.split(',')
            author = meta[0].replace('By', '').strip()
            email = slugify(author) + self.email_suffix
            date_at = tools.revert_humanize_datetime(meta[1].strip())
            if not date_at:
                datetime = timezone.now()
            article = dict(
                blog_id=blog_id,
                title=title,
                url=url,
                author=author,
                email=email,
                featured_media=media,
                published_at=date_at)
            print(article)
            self.stdout.write(
                self.style.SUCCESS('get article "%s",waiting parse' % title))
            self.parse_article(article)

    def parse_article(self, article):
        html = tools.get_content(article['url'], True)
        if not html:
            logging.error("can't get url " + article['url'])
        soup = BeautifulSoup(html, "html.parser")
        content = soup.find('div', class_='post-content')
        article['content'] = str(content)
        wp.save_post(article)

    def handle(self, *args, **options):
        from_page = options['from_page']
        while from_page >= 2:
            url = self.host + 'page/' + str(from_page) + '/'
            self.parse_page(url)
            from_page -= 1
            break
        self.parse_page(self.host)
